import datetime
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models
from django.shortcuts import render, redirect


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """
        如果用户已登录，则在request中赋值
        :param request:
        :return:
        """

        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object

        # 白名单：没登录也可以访问的url
        white_list = settings.WHITE_REGEX_URL_LIST
        # print(request.path_info)
        if request.path_info in white_list:
            return

        # 检查用户是否已登录，未登录则返回登录页面
        if not user_object:
            return redirect('login')

        # 登录成功之后，访问后台管理时，获取当前用户所拥有的额度
        # 方式一：免费额度在交易记录中存储
        # 获取当前用户ID最大（最近交易记录）
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()

        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()

        # request.transaction = _object
        request.tracer.price_policy = _object.price_policy

        # 方式二：免费的额度存储配置文件
        # _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        #
        # if not _object:
        #     # 没有购买
        #     request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # else:
        #     # 有购买记录
        #     current_datetime = datetime.datetime.now()
        #     if _object.end_datetime and _object.end_datetime < current_datetime:
        #         request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        #     else:
        #         request.price_policy = _object.price_policy
